import { useEffect, useRef, useState } from "react";
import http from "../http";
import { Button, Form, Toast } from "@douyinfe/semi-ui";
import { ISetting } from "../types";

function Setting() {
  const formApiRef = useRef<any>(null);
  const [setting, setSetting] = useState<ISetting>();

  useEffect(() => {
    http.get("/settings").then((x) => {
      setSetting(x.data);
      formApiRef.current.setValues(x.data)
    });
  }, []);
  const handleSubmit = (values: ISetting) => {
    http.post("/settings", values).then(()=> {
      Toast.success("ok")
    })
  };
  return (
    <div style={{padding: '3px'}}>
      <Form initValues={setting} onSubmit={(values) => handleSubmit(values)} labelPosition={"left"} getFormApi={(formApi) => (formApiRef.current = formApi)}>
        {({ formState }: { formState: Record<string, any> }) => (
          <>
            <Form.Input field="dataPath" label="存储位置"></Form.Input>
            <Form.InputNumber field="port" label="api端口"></Form.InputNumber>
            <Form.Checkbox
              field="useAccessPassword"
              label="访问密码"
            ></Form.Checkbox>
            {formState.values["useAccessPassword"] == true && (
              <div>
                <Form.Input field="accessPassword" label="应用访问密码"></Form.Input>
                <Form.Input
                  field="fileAccessPassword"
                  label="文件访问密码"
                ></Form.Input>
              </div>
            )}
            <Button htmlType="submit">保存</Button>
          </>
        )}
      </Form>
    </div>
  );
}

export default Setting;
